package service_book

import (
	"fmt"
	"strconv"
	"strings"
	"tools-api/src/common/db/database"
)

// sort 更新排序 通用方法
func sort(table string, uuid string, list [][]int64) error {
	if len(list) == 0 {
		return nil // 空列表直接返回
	}

	// 1. 构建批量更新SQL
	// 格式：UPDATE book_types SET sort = CASE id WHEN ? THEN ? WHEN ? THEN ? ... END WHERE id IN (?, ?, ...)
	var cases []string // 存储CASE语句片段
	var ids []string   // 收集所有id，用于WHERE条件

	for _, item := range list {
		id := item[0]   // id
		sort := item[1] // 对应sort的值
		ids = append(ids, strconv.FormatInt(id, 10))
		cases = append(cases, fmt.Sprintf("WHEN %d THEN %d", id, sort))
	}
	idsStr := strings.Join(ids, ",")

	// 拼接CASE语句
	caseStr := fmt.Sprintf("CASE id %s END", strings.Join(cases, " "))

	sql := fmt.Sprintf("UPDATE %s SET sort = %s where  id in (%s) and uuid= '%s'", table, caseStr, idsStr, uuid)
	// 2. 执行批量更新
	_, err := database.JCJEngine.Exec(sql)
	if err != nil {
		return fmt.Errorf("批量更新失败: %w", err)
	}
	return nil
}
